package com.tianshi.agriculture;

import android.Manifest;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.tianshi.agriculture.adapter.BluetoothDeviceAdapter;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.BleController;
import com.tianshi.agriculture.utils.Ble.hansion.h_ble.callback.ConnectCallback;
import com.tianshi.agriculture.utils.ModbusUtils.ByteUtil;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class BluetoothScanActivity extends AppCompatActivity  implements AdapterView.OnItemClickListener {

    private Button startQueryButton;
    private Button openBluetooth;
    private final static int REQUEST_ENABLE_BT = 1;
    private BluetoothGatt bluetoothGatt;
    private List<BluetoothDevice> bondedDevices = new ArrayList<>();
    private List<BluetoothDevice> unbondedDevices = new ArrayList<>();
    private BluetoothAdapter bluetoothAdapter = null;
    private BluetoothDevice currentDevice = null;
    private BluetoothSocket bluetoothSocket = null;
    private BleController mBleController;
    public static final String REQUESTKEY_SENDANDRECIVEACTIVITY = "ModbusByBlueToothActivity";
    private ListView mDeviceList = null;
    private ProgressDialog progressDialog;
    private int REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_bluetooth_scan);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        //悬浮窗权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(!Settings.canDrawOverlays(BluetoothScanActivity.this)){
                //判断是否能绘制在所有布局上
                Toast.makeText(BluetoothScanActivity.this,"请授权悬浮窗",Toast.LENGTH_SHORT).show();
                startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 2333);
            }
        }

        mBleController = BleController.getInstance().init(this);

        checkPermission();

//        int testInt  = -1886846095;
//        byte[] buffers = ByteUtil.fromInt32(testInt);
//        System.out.println(BleController.getInstance().bytesToHexString(buffers));
//
//        long testLong = ByteUtil.bytesToUint32(buffers);
//        System.out.println(testLong);

        testNumberExchange();

        //隐藏标题栏
        //this.findViewById(R.id.top_view_container).setVisibility(View.INVISIBLE);

        startQueryButton = (Button) this.findViewById(R.id.start_query_button);

        mDeviceList = (ListView) this.findViewById(R.id.mDeviceList);
        if (!getPackageManager().hasSystemFeature(   //判断主机是否支BLE牙设备
                PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "BLE is not supported", Toast.LENGTH_SHORT)
                    .show();
            finish();

        }

        if (ActivityCompat.checkSelfPermission(BluetoothScanActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(BluetoothScanActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(BluetoothScanActivity.this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_CODE);
            }
        }

        // 初始化蓝牙适配器
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            // 设备不支持蓝牙
            return;
        }

        // 确保蓝牙已经开启
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }

        // 获取已配对的设备列表


        startQueryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (startQueryButton.getText().equals("开始扫描")) {


                    // 确保蓝牙已经开启
                    if (!bluetoothAdapter.isEnabled()) {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                        return;
                    }


                    // 获取已配对的设备列表
                    if (ActivityCompat.checkSelfPermission(BluetoothScanActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                        if (ContextCompat.checkSelfPermission(BluetoothScanActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(BluetoothScanActivity.this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_CODE);
                        }
                    }
                    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
                    if (pairedDevices.size() > 0) {
                        for (BluetoothDevice device : pairedDevices) {
                            // 连接设备
                            // ...
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                                System.out.println(device.getName() + "," + device.getAddress() + "," + device.getAlias() + "," + device.getType());
                            }
                        }
                    }
                    // 获取已绑定的设备列表
                    bondedDevices.addAll(bluetoothAdapter.getBondedDevices());

                    // 开始扫描可连接的设备
                    boolean b = bluetoothAdapter.startLeScan(mLeScanCallback);


                    unbondedDevices.clear();

                    mDeviceList.setAdapter(new BluetoothDeviceAdapter(BluetoothScanActivity.this, unbondedDevices));
                    mDeviceList.setOnItemClickListener(BluetoothScanActivity.this);


                    startQueryButton.setText("停止扫描");
                }
                else if(startQueryButton.getText().equals("停止扫描"))
                {
                    bluetoothAdapter.stopLeScan(mLeScanCallback);
                    startQueryButton.setText("开始扫描");
                }
            }
        });


//        TextView top_view_text = (TextView)findViewById(R.id.top_view_text);
//        top_view_text.setText("扫描蓝牙");
//        top_view_text.setVisibility(View.VISIBLE);
    }


    BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {


            if (ActivityCompat.checkSelfPermission(BluetoothScanActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(BluetoothScanActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(BluetoothScanActivity.this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_CODE);
                }
            }

            if (device.getName() != null &&
                    (device.getName().contains("Ai-Thinker") ||
                    (device.getName().length() == 10 && isNumericName(device.getName())) ||
                    (device.getName().equals("0"))
                    )
               ) {
                Log.d("蓝牙设备=====>", device.getName() + "\n" + device.getAddress());
                boolean isSaved = false;
                for (int i = 0; i < unbondedDevices.size(); i++) {
                    if (unbondedDevices.get(i).getAddress().equalsIgnoreCase(device.getAddress())) {
                        isSaved = true;
                        break;
                    }
                }

                if (isSaved == false) {
                    unbondedDevices.add(device);

                    try {
                        ((BluetoothDeviceAdapter) mDeviceList.getAdapter()).notifyDataSetChanged();
                    }
                    catch(Exception ex) {
                        ex.printStackTrace();
                    }

                }
            }
        }
    };

    public static boolean isNumericName(String name) {
        return name.length() == 10 && name.matches("\\d+");
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        showProgressDialog("请稍等", "正在连接...");

        try {
            mBleController.closeBleConn();
        }
        catch(Exception ex) {
        }


        // TODO 第三步：点击条目后,获取地址，根据地址连接设备
        String address = unbondedDevices.get(position).getAddress();
        mBleController.connect(0, address, new ConnectCallback() {
            @Override
            public void onConnSuccess() {
                hideProgressDialog();
//                Toast.makeText(BluetoothScanActivity.this, "连接成功!", Toast.LENGTH_SHORT).show();

//                if(startQueryButton.getText().equals("停止扫描")) {
//                    startQueryButton.performClick();
//                }
                startActivity(new Intent(BluetoothScanActivity.this, OperationActivity.class));
            }

            @Override
            public void onConnFailed() {
                hideProgressDialog();
                Toast.makeText(BluetoothScanActivity.this,  "连接失败!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void showProgressDialog(String title, String message) {
        if (progressDialog == null) {
            progressDialog = ProgressDialog.show(this, title, message, true, false);
        } else if (progressDialog.isShowing()) {
            progressDialog.setTitle(title);
            progressDialog.setMessage(message);
        }
        progressDialog.show();
    }

    public void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideProgressDialog();
    }

    private void testNumberExchange()
    {
        int signedNumber = -1886846095;
        // 创建一个 ByteBuffer，并将有符号整数写入其中
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.putInt(signedNumber);
        // 切换到大端字节序（如果需要）
        buffer.order(ByteOrder.BIG_ENDIAN);
        byte[] buffers = new byte[8];
        byte[] oldBytes = buffer.array();
        buffers[0] = 0;
        buffers[1] = 0;
        buffers[2] = 0;
        buffers[3] = 0;
        buffers[4] = oldBytes[0];
        buffers[5] = oldBytes[1];
        buffers[6] = oldBytes[2];
        buffers[7] = oldBytes[3];

        long l = ByteUtil.bytesToInt64(buffers);

        System.out.println(ByteUtil.toHexString(buffer.array()));

        int a = 0 ;
    }
}